

from emtencent import em_classified
from sysdata import sys_base_data as sysBaseData
from emmodels.em_base_data import ModuleData
import emmongo.em_mongomanager as emMongoManager
import pandas as pd
import pymongo



# class ShiZiXingDetectThread(threading.Thread):
#
#     def __init__(self, module_items):
#         self.module_items = module_items
#
#     def run(self):
#         stks = []
#         for item in self.module_items:
#             if isinstance(item, ModuleData):
#                 [stks.append(x) for x in item.module_stk_codes if x not in stks]
#         # ts.get_today_all()
#
#
# class CurHotDetectThread(threading.Thread):
#
#     def __init__(self):
#         pass
#
#     def run(self):
#         pass

def caculate_cur_hot(self):
    for i in [1 ,2]:
        df = em_classified.get_tc_top_least_code(type=i)
        self.save_module(df)

module_dic = {}
stk_dic = {}
THROLD = 0.01
UPPCTTHROLD = 0.6
STK_ADD_SCORE = 1
MODULE_ADD_SCORE = 1


def save_module(self, df):
    if not isinstance(df, pd.DataFrame):
        return
    for index, item in df.iterrows():
        module = sysBaseData.get_module(item['module_code'])
        if not module:
            continue
        module.set_with_dict(forceUpdate=True, **(item.to_dict()))
        if float(module.zdf) > THROLD and module.up_pct > UPPCTTHROLD:
            module.score += MODULE_ADD_SCORE
            module.saveToMongo()
        if module.module_code in self.module_score_descend_list(maxcount=30):
            self.score_lzg(item.to_dict())


def module_score_descend_list(self, maxcount = 5):
    cursor = ModuleData.select_all_from_mongo()
    datas = list(cursor.sort([('last_update_time', pymongo.DESCENDING), ('score', pymongo.DESCENDING)]).limit(maxcount))
    return [x['module_code'] for x in datas]


def score_lzg(self, item):
    stk_code = item['top_zf_gu']
    sfund = sysBaseData.get_self_fund(stk_code)
    sfund.score += STK_ADD_SCORE
    sfund.saveToMongo(tb_name=emMongoManager.COL_SELF_FUND)